package com.huisang.service.impl;


import com.huisang.domain.Emp;
import com.huisang.mapper.EmpMapper;
import com.huisang.service.EmpService;
import com.huisang.util.MD5Util;
import com.huisang.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    /**
     * 注册事务
     * @param emp
     * @return
     */
    @Override
    public int addEmp(Emp emp) {
        Emp empByUsername = empMapper.findEmpByUsername(emp.getUsername());
        try {
            if(empByUsername == null) { //查不到开始注册
                int i = empMapper.addEmp(emp);
                return i;
            }else {
                return -1;  //用户名已存在
            }
        } catch (Exception e) {
            return -2;  //添加失败
        }

    }

    /**
     * 登录事务
     * @param emp
     * @return 返回登录者的id
     */
    @Override
    public int login(Emp emp) {

        try {
            Emp empByUsername = empMapper.findEmpByUsername(emp.getUsername());
            if(empByUsername.getPasswd().equals(emp.getPasswd())) {
                return empByUsername.getEid();
            }
            return -1;
        } catch (Exception e) {
            return -2;
        }

    }

    @Override
    public Emp findEmpByEid(Emp emp) {
        Emp empByEid = empMapper.finEmpByEid(emp.getEid());
        empByEid.setPasswd("");
        return empByEid;
    }

    @Override
    public ResponseEntity<Integer> updatePassword(Emp emp, String newPassword) {
        ResponseEntity<Integer> responseEntity = new ResponseEntity<>();
        //将前端老密码加密放入
        emp.setPasswd(MD5Util.toMd5(emp.getPasswd()));
        //根据id查找顾客，用于判断老密码是否正确
        Emp finEmpByEid = empMapper.finEmpByEid(emp.getEid());

        if(finEmpByEid.getPasswd().equals(emp.getPasswd())) {   //密码相同验证成功
            //将新密码加密
            emp.setPasswd(MD5Util.toMd5(newPassword));
            int i = empMapper.updatePassword(emp);
            if(i > 0) {
                responseEntity.setCode(200);
                responseEntity.setMessage("修改密码成功！");
                responseEntity.setData(i);
                return responseEntity;
            }
            responseEntity.setCode(500);
            responseEntity.setMessage("修改密码失败！服务器错误！");
            responseEntity.setData(i);
            return responseEntity;
        }
        responseEntity.setCode(500);
        responseEntity.setMessage("修改密码失败！旧密码输入错误！");
        responseEntity.setData(-1);
        return responseEntity;
    }
}
